<template>
  <div>
    <el-dialog
      :visible="visible"
      :title="handlerSubmit.name === 'add' ? '添加数据' : handlerSubmit.name === 'read'?'查看数据':'编辑数据'"
      width="30%"
      @close="$emit('update:visible', false)"
    >
      <!-- 添加/编辑的表单 -->
      <el-form
        v-if="handlerSubmit.name !== 'read'"
        ref="form"
        :model="formData"
        label-width="80px"
        :rules="rules"
        label-position="top"
      >
        <el-form-item
          v-for="(item, index) in formOptionItems"
          :key="index"
          :label="item.label"
          :prop="item.type === 'timer' ? 'timer' : item.name"
        >
          <!-- 根据字段类型选择合适的组件 -->
          <el-input
            v-if="item.type === 'text'"
            v-model="formData[item.name]"
            :placeholder="'请输入' + item.label"
          />
          <el-select
            v-if="item.type === 'select'"
            v-model="formData[item.name]"
            :placeholder="'请选择' + item.label"
            style="width: 100%"
          >
            <el-option
              v-for="v in item.options"
              :key="item.handler ? v[item.handler.value] : v.value"
              :label="item.handler ? v[item.handler.label] : v.label"
              :value="item.handler ? v[item.handler.value] : v.value"
            />
          </el-select>
          <el-date-picker
            v-if="item.type === 'timer'"
            v-model="formData.timer"
            size="small"
            style="width: 100%"
            :type="'datetimerange'"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            @change="
              () => {
                if (!formData.timer) {
                  formData[item.name[0]] = '';
                  formData[item.name[1]] = '';
                } else {
                  formData[item.name[0]] = formData.timer[0];
                  formData[item.name[1]] = formData.timer[1];
                }
              }
            "
          />
        </el-form-item>
      </el-form>
      <!-- 查看数据的表单 -->
      <el-form v-else label-width="120px" label-position="right">
        <el-form-item
          v-for="(item, index) in onlyReadFormItems"
          :key="index"
          :label="item.label + ':'"
        >
          <!-- 根据字段类型选择合适的组件 -->
          <!-- <el-input type="text" :value="formData[item.name]" /> -->
          <div v-if="item.separator">
            <span
              v-for="(v, index) in item.name"
              :key="index"
            >{{ formData[v] }}
              <span>{{
                index !== item.name.length - 1 ? item.separator : ""
              }}</span></span>
          </div>
          <span>{{ formData[item.name] }}</span>
        </el-form-item>
      </el-form>
      <!-- dialog底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="$emit('update:visible', false)">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'MyDialog',
  props: {
    visible: Boolean,
    formOptionItems: {
      type: Array,
      default() {
        return []
      }
    }, // 添加、编辑的表单项配置
    onlyReadFormItems: Array, // 查看的表单项配置
    handlerSubmit: Object // 表单提交配置
  },
  data() {
    return {
      // 表单校验规则
      rules: {},
      // 表单绑定数据
      formData: {
        timer: ''
      }
    }
  },
  watch: {
    // 监听弹出框关闭，重置表单和数据
    visible(value) {
      if (value === false) {
        this.$refs.form.resetFields()
        this.formData = {
          timer: ''
        }
      }
    },
    // 获取表单回填数据 监听表单提交配置项中的name字段
    async 'handlerSubmit.name'(val) {
      if (val === 'edit' || val === 'read') {
        this.formData = await this.getDetailAPI(this.handlerSubmit.detailUrl)
      }
    }
  },
  async created() {
    this.getRules()
    this.handlerItemData()
  },
  methods: {
    // 生成表单项的校验规则
    getRules() {
      this.formOptionItems.forEach((item) => {
        if (item.type === 'select') {
          this.rules[item.name] = [
            {
              required: true,
              message: '请选择' + item.label,
              trigger: 'change'
            }
          ]
        } else if (item.type === 'timer') {
          this.rules.timer = [
            {
              required: true,
              message: '请选择' + item.label,
              trigger: 'change'
            }
          ]
        } else {
          this.rules[item.name] = [
            { required: true, message: '请输入' + item.label, trigger: 'blur' }
          ]
          if (item.rule) {
            this.rules[item.name].push(item.rule)
          }
        }
      })
    },
    // 表单提交操作
    handleSubmit() {
      // 查看 提交直接关闭弹框
      if (this.handlerSubmit.name === 'read') {
        this.formData = {}
        this.$emit('update:visible', false)
        return
      }
      this.$refs.form.validate(async(valid) => {
        // 校验数据
        if (valid) {
          // 移除组件定义的表单中timer字段
          delete this.formData.timer
          if (this.handlerSubmit.name === 'add') {
            // 调添加接口
            await this.addInfoAPI(this.handlerSubmit.url)
          }
          if (this.handlerSubmit.name === 'edit') {
            // 调编辑接口
            await this.updateInfoAPI(this.handlerSubmit.url)
          }
          // 提示用户
          this.$message.success('操作成功!')
          // 刷新列表
          this.$emit('onFormSubmit')
          // 关闭弹出框
          this.$emit('update:visible', false)
        }
      })
    },
    // 表单项数据添加options字段
    handlerItemData() {
      this.formOptionItems.forEach(async(item) => {
        if (item.type === 'select' && item.handler) {
          // eslint-disable-next-line require-atomic-updates
          item.options = await this.getOptionsAPI(item.handler.url)
        }
      })
    },
    // 获取表单下拉框数据API
    async getOptionsAPI(url) {
      const res = await request({
        url
      })
      // 后台响应的数据rows是下拉款的数据情况
      if (res.rows) {
        return res.rows
      }
      return res
    },
    // 添加API
    addInfoAPI(url) {
      return request({
        url,
        method: 'post',
        data: this.formData
      })
    },
    // 获取详情API
    getDetailAPI(url) {
      return request({
        url
      })
    },
    // 更新API
    updateInfoAPI(url) {
      return request({
        url,
        method: 'put',
        data: this.formData
      })
    }
  }
}
</script>

<style>
</style>
